package multithreading;

import java.util.ArrayList;
import java.util.List;

public class Demo6_FindPrimeNum {

    public static void main(String[] args) throws InterruptedException {

        //创建三个独立的线程
        Thread first = new Thread(new PrimeNumber(2,1000));
        Thread second = new Thread(new PrimeNumber(1001,2000));
        Thread third = new Thread(new PrimeNumber(2001,3000));

        //开启三个线程
        first.start();
        second.start();
        third.start();

        //让主线程最后执行
        first.join();
        second.join();
        third.join();

        System.out.println(PrimeNumber.listPrimeNumber);
        System.out.println(PrimeNumber.listPrimeNumber.size());

    }

}


class PrimeNumber implements Runnable{

    //初始化一个静态变量，用来存储所有的素数
    static List<Integer> listPrimeNumber = new ArrayList<>();

    int startNum;
    int endNum;

    public PrimeNumber(int startNum, int endNum) {
        this.startNum = startNum;
        this.endNum = endNum;
    }

    @Override
    public void run() {

        boolean flag = true;
        for (int i = this.startNum; i <= this.endNum ; i++) {
            for (int j = 2; j <= i/2 ; j++) {
                if(i % j == 0){
                    flag = false;
                    break;
                }
            }
            if(flag){
                listPrimeNumber.add(i);
            }else{
                //如果不是素数，要把表示复位
                flag = true;
            }
        }

    }
}
